package com.bzs.batch.reconcile.batch.itemwriter;

import com.bzs.batch.reconcile.entity.HostFile;
import lombok.AllArgsConstructor;
import org.springframework.batch.item.ItemWriter;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @Classname ItemWriterFile
 * @Author baozs
 * @Date 2021/12/22 15:17
 * @Version 1.0
 * @Description
 **/
@Service
@AllArgsConstructor
public class ItemWriterFile implements ItemWriter<HostFile> {

    private final JdbcTemplate jdbcTemplate;


    /**
     * @param items 文件中读取到的HostFile
     * @throws Exception 异常处理
     */
    @Override
    public void write(List<? extends HostFile> items) throws Exception {
        System.out.println("Host系统对账文件开始入库");
        String sql = "INSERT INTO host_transactionflow " +
                "(all_serialno, host_seriano, " +
                "debit_account, credit_account, " +
                "trade_data, trade_time," +
                " host_trade_result, trans_amount)" +
                "VALUES (?,?,?,?,?,?,?,?)";

        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

            /**
             * @param ps 参数
             * @param i  索引，从0开始
             * @throws SQLException 异常
             */
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                HostFile hostFile = items.get(i);
                System.out.println("Host系统对账文件流水号：" + hostFile.getAllSerialno());
                ps.setString(1, hostFile.getAllSerialno());//全局流水号
                ps.setString(2, hostFile.getHostSeriano());//核心流水号
                ps.setString(3, hostFile.getDebitAccount());//借方账户
                ps.setString(4, hostFile.getCredit());//贷方账户
                ps.setString(5, hostFile.getTradeData());//核心交易日期
                ps.setString(6, hostFile.getTradeTime());//核心交易时间
                ps.setString(7, hostFile.getHostTradeResult());//核心交易结果
                ps.setString(8, hostFile.getTransAmount());//交易金额
            }

            /**
             * @return 批量数
             */
            @Override
            public int getBatchSize() {
                System.out.println("Host文件数据数量为：" + items.size());
                return items.size();
            }
        });
    }
}
